<template>
  <div class="macarons" style="width: 100%; height: 450px;" />
</template>

<script>
import echarts from 'echarts';
import { cityTop } from '@/api/home';
require('echarts/theme/macarons'); // echarts theme
import resize from '../components/mixins/resize';

export default {
  mixins: [resize],
  props: {
    chartData: {
      type: Array
    },
    channelId: {
      type: Number
    }
  },
  data() {
    return {
      chart: null,
      listQuery: {
        startTime: this.chartData.startTime,
        endTime: this.chartData.endTime,
        channelId: this.channelId
      },
      cityData: []
    };
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.listQuery.startTime = this.chartData.startTime;
        this.listQuery.endTime = this.chartData.endTime;
        this.getCityityTop();
      }
    },
    channelId: {
      deep: true,
      handler(val) {
        this.listQuery.channelId = val;
        this.getCityityTop();
      }
    }
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    async getCityityTop() {
      const res = await cityTop(this.listQuery);
      if (res.data.code === 200) {
        this.city = res.data.data.city;
        this.cityData = res.data.data.data;
        this.initChart();
      }
    },
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons');
      this.setOptions(this.chartData);
    },
    setOptions({ expectedData, actualData } = {}) {
      this.chart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '5%',
          bottom: '4%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          boundaryGap: [0, 0.001]
        },
        yAxis: {
          type: 'category',
          data: this.city
        },
        series: [
          {
            type: 'bar',
            color: '#376DF7',
            lable: {
              show: true,
              position: 'right'
            },
            data: this.cityData
          }
        ]
      });
    }
  }
};
</script>
